import { ReactView, reactControl, ReactViewControl, ReactViewState } from "pao-aop-client";

import React from "react";

import { addon, Ref, getObject, log } from "pao-aop";
import moment from 'moment';
import 'moment/locale/zh-cn';
import { message, Menu } from "antd";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import { IExternalLinkSignService, ExternalLinksSign } from "src/models/externalLinksSign";
import { ProductSignCondition } from "src/models/singleProductSign";
import { onRowSkipClick, ROUTE_PATH } from "../../app/util-tool";
import { ClickParam } from "antd/lib/menu";
moment.locale('zh-cn');

export interface ExternalLinksViewState extends ReactViewState {
    /** 跳转列表数据源 */
    data_source: ExternalLinksSign[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: ExternalLinksSign;
    /** 行选中对象 */
    row_select_data?: any;
    /** 行操作使能 */
    row_operation_enable?: boolean;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：跳转标识页面
 */
export class ExternalLinksView extends ReactView<ExternalLinksViewControl, ExternalLinksViewState> {

    private columns_data_source = [
        {
            title: '跳转名称',
            dataIndex: 'handle_name',
            key: "handle_name",
            width: 500
        },
        {
            title: '跳转标识',
            width: 500,
            dataIndex: 'handle_code',
            key: 'handle_code',
            render: (text: string, record: any, index: any) => {
                return <a onClick={() => onRowSkipClick(this.props, record, index, ROUTE_PATH.externalLinksDetail)}>{text}</a>;
            }
        },
        {
            title: '创建时间',
            width: 150,
            dataIndex: 'create_date',
            key: 'create_date',
        }
    ];

    constructor(props: any) {
        super(props);
        this.state = {
            data_source: [],
            page: 1,
            pageSize: 10,
            row_operation_enable: true,
            row_select_data: [],
            loading: false
        };
    }

    /** 
     * 分页回调事件 
     */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("externalLinksViewControl", error.message);
            });
    }

    /** 
     * 改变分页数量回调事件 
     */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("externalLinksViewControl", error.message);
            });
    }

    externLinkServices?() {
        return getObject(this.props.externalLinkService_Fac!);
    }

    async queryList(condition: ProductSignCondition, page: number, count: number) {
        const data = await this.externLinkServices!()!.get_external_link_list!(condition, page, count)!;
        this.setState({
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data.result! : [],
            row_operation_enable: true
        });
    }

    /**
     * 查询回调
     */
    private searchExternLink = (e: any, val: any) => {
        this.setState({
            condition: val,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("externalLinksViewControl", error.message);
            });
    }

    /**
     * table其他按钮回调
     */
    private handleOtherClick = (type: any, contents: any) => {
        /** 自定义图标按钮回调事件 */
        if ('icon_edit' === type) {
            console.log('自定义按钮edit返回值：', contents);
            this.editCategory(contents);
        }
    }

    /**
     * 创建新跳转回调
     */
    private createExternLink = () => {
        console.log("创建新跳转回调");
        this.props.history!.push!(ROUTE_PATH.changeExternalLinks);
    }

    /**
     * 编辑行的类目回调
     */
    private editCategory = (record: any) => {
        console.log("编辑行的类目回调");
        console.log(record);
        this.props.history!.push(ROUTE_PATH.changeExternalLinks + `/${record.id}`);
    }

    /**
     * 删除跳转回调
     */
    private deleteCategory = (record: any) => {
        this.setState({
            loading: true
        });
        console.log("删除跳转回调");
        console.log(record);
        let ids: string[] = [];
        if (!Array.isArray(record)) {
            ids.push(record.id);
        } else {
            ids = record;
        }
        this.externLinkServices!()!.delete_external_link!(ids)!
            .then(info => {
                if (info) {
                    message.info("删除成功");
                    // this.loadInfo();
                    this.queryList({}, 1, 10)
                        .then(() => {
                            this.setState({
                                loading: false
                            });
                        })
                        .catch(error => {
                            this.setState({
                                loading: false
                            });
                            log("externalLinksViewControl", error.message);
                        });
                } else {
                    message.error("删除失败");
                }
            }
            )
            .catch(error => {
                this.setState({
                    loading: false
                });
                console.log(error);
            });
    }

    /**
     * 重置回调
     */
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {},
            loading: true
        });
        this.queryList({}, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("externalLinksViewControl", error.message);
            });
    }

    componentDidMount() {
        this.setState({
            loading: true
        });
        let condition: ProductSignCondition = {};
        this.queryList(condition, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("externalLinksViewControl", error.message);
            });
    }

    /** 批量操作 */
    private handleMenuClick = (e: ClickParam) => {
        console.log('click', e);
        if (e.key === "delete") {
            let ids: string[] = this.state.row_select_data.map((e: ExternalLinksSign, i: any) => e.id);
            this.setState({ row_operation_enable: false });
            this.deleteCategory(ids);
        }
    }

    /** 行选中回调 */
    private handleRowSelect = (e: any) => {
        console.log(e);

        if (e.length === 0) {
            this.setState({
                row_operation_enable: true
            });
        } else {
            this.setState({
                row_select_data: e,
                row_operation_enable: false
            });
        }
    }

    render() {
        let { data_source, total_data } = this.state;

        const menu = (
            <Menu onClick={this.handleMenuClick}>
                <Menu.Item key="delete">删除</Menu.Item>
            </Menu>
        );

        let sign_frame_props = {
            loading: this.state.loading,
            edit_form_items_props: [{
                type: InputType.input,
                label: "跳转标识名称",
                decorator_id: "handle_name",
                option: {
                    placeholder: "请输入跳转标识名称"
                }
            },
            {
                type: InputType.input,
                label: "跳转标识",
                decorator_id: "handle_code",
                option: {
                    placeholder: "请输入跳转标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date",
            }],
            btn_props: [
                {
                    label: '新建跳转标识',
                    btn_method: this.createExternLink,
                    icon: 'plus'
                }
            ],
            draw_down_btn: {
                menu: menu,
                label: "批量操作",
                enable: this.state.row_operation_enable
            },
            showTable: (
                <NTOperationTable
                    data_source={data_source}
                    on_row_selection={this.handleRowSelect}
                    columns_data_source={this.columns_data_source}
                    bordered={false}
                    on_click_del={this.deleteCategory}
                    // onClick={this.onRowClick}
                    on_icon_click={this.handleOtherClick}
                    other_label_type={[{ type: 'icon', label_key: 'icon_edit', label_parameter: { icon: 'antd@edit' } }]}
                    table_size='middle'
                    showHeader={true}
                    total={total_data}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                    rowKey='id'
                />),
            search_cb: this.searchExternLink,
            reset_cb: this.reset
        };

        return (
            <SignFrameLayout {...sign_frame_props} />
        );
    }
}

/**
 * 控件：跳转标识视图页面
 * @description 跳转标识页面
 * @author cxl
 */
@addon('ExternalLinksView', '监控台视图页面', '跳转标识页面')
@reactControl(ExternalLinksView, true)
export class ExternalLinksViewControl extends ReactViewControl {
    /**
     * 跳转标识服务
     */
    public externalLinkService_Fac?: Ref<IExternalLinkSignService>;
}